<?php

namespace App\Http\Controllers\Admin\Framework\Manage;

use App\Http\Controllers\Admin\ParentController;
use App\Master\Framework\Extend\Core;
use App\Master\Framework\View\AdminData;
use App\Models\Admin\Framework\AdminAccessLogModel;
use App\Models\Admin\Framework\AdminLoginLogModel;
use App\Utils\ExcelCsv;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LogController extends ParentController
{

    public function __construct(array $attributes = [])
    {
        parent::__construct();
    }

    public function login(Request $request)
    {
        if ($request->isMethod('post')) {
            $query = AdminLoginLogModel::query()->select(['id', 'account', 'code', 'msg', 'ip', 'region', 'browser', 'created_at']);

            if ($request->keyword) {
                $query->where('account', 'like', '%' . $request->keyword . '%');
            }

            if ($request->code) {
                if ($request->code == '1') {
                    $query->where('code', 200);
                } else {
                    $query->where('code', '!=', 200);
                }
            }

            if ($request->date) {
                $query->whereDate('created_at', $request->date);
            }

            // 自动排序
            if ($orderBy = AdminData::orderBy()) {
                foreach ($orderBy as $order){
                    $query->orderBy($order['sort'], $order['orderBy']);
                }
            }

            $list = $query->paginate($request->size);

            Core::jsonResponse(200, 'success', $list);
        } else {
            return view('admin.framework.manage.log.login');
        }
    }

    public function loginClear(Request $request)
    {
        if ($request->isMethod('post')) {
            AdminLoginLogModel::truncate();

            Core::jsonResponse(200, 'success');
        }
    }

    public function access(Request $request)
    {
        if ($request->isMethod('post')) {
            $query = AdminAccessLogModel::query();
            if ($request->keyword) {
                $query->where('account', 'like', '%' . $request->keyword . '%');
            }
            if ($request->date) {
                $query->whereDate('created_at', $request->date);
            }

            // 自动排序
            if ($orderBy = AdminData::orderBy()) {
                foreach ($orderBy as $order){
                    $query->orderBy($order['sort'], $order['orderBy']);
                }
            }

            Core::jsonResponse(200, 'success', $query->paginate($request->size));
        } else {
            return view('admin.framework.manage.log.access');
        }
    }

    public function accessClear(Request $request)
    {
        if ($request->isMethod('post')) {
            AdminAccessLogModel::query()->truncate();

            Core::jsonResponse(200, 'success');
        }
    }
}
